﻿/// <reference path="Meres.js" />

people = function () {

    this.installPluggin = function () {
        installjQueryPlugin();
    };

    this.perform = function (evt) {
        if (evt == undefined)
            return;
        openPersonDetail();
    };

    installjQueryPlugin();

    var preventSelPerson = false;
    function installjQueryPlugin() {
        $("#peopleView .personSelector").personSelector(
        {
            selectedChanged: function () {
                if (preventSelPerson)
                    return;
                var selPerson = $("#peopleView .personSelector").personSelector('option', 'getSelPerson');
                if (selPerson.length == 0)
                    return;
                setSelPersonId(selPerson[0]);
            },
            selCategoryChanged: function (paras) {
                var selView = getSelectedMode();
                var selCats = $("#peopleView .personSelector").personSelector('option', 'getSelCategories');

                if (selView == 1) {
                    openPeopleList({ catIds: selCats });
                }
                else if (selView == 0) {
                    openCardView({ catIds: selCats });
                }
            }

        });
        $("#peopleView .peopleFunctions").selectable();

        $('.peopleView').layout({
            center: {
                onresize: "innerLayout.resizeAll"
            }
        });

        var layout = $('#peopleView .innerLayout').layout({
            center: {
                onresize: "innerLayout.resizeAll"
            }
        });
        layout.sizePane("north", "28");

        $('.peopleView .tools').accordion({ fillSpace: true });

        renderActionBar(
            {
                target: '.peopleView .actionBar',
                commands: ['add', 'clone', 'delete', 'save'],
                viewModes: ['iconView', 'listView', 'detailPersonView'],
                viewModeSelected: function () {
                    var selView = getSelectedMode();
                    var selCats = $("#peopleView .personSelector").personSelector('option', 'getSelCategories');

                    if (selView == 1) {
                        openPeopleList({ catIds: selCats });
                    }
                    else if (selView == 0) {
                        openCardView({ catIds: selCats });
                    }
                    else {
                        openPersonDetail(getSelPersonId());
                    }
                }
            });

        installCombobox();

        $('.peopleView .actionBar .save').click(function () {
            if (contextInfo.Module == 'PersonDetail') {
                savePersonInfo();
            }
        });
        
        $('.peopleView .actionBar .add').click(function () {

            var url1 = '/Meres/People/NewPersonControl';
            var url2 = '/Meres/People/AddNewPerson';
            // Get HTML form
            doAjax(url1, showForm);

            function showForm(evt) {
                $("#dialog-form").dialog({
                    autoOpen: false,
                    height: 200,
                    width: 400,
                    modal: true,
                    buttons: {
                        OK: executeCreateNew,
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });

                $("#dialog-form").html(evt);
                installCombobox();
                $("#dialog-form").dialog("open");
            }

            function executeCreateNew() {
                doAjax(url2,
                            function (evt) {
                                $('#dialog-form').dialog("close");
                                Messenger.broadcast(this, Messenger.PERSON_ADDED, evt);
                                // Do other stuff, refresh UI
                            },
                            $('#newPersonForm').serialize());
            }
        });
    }

    function getSelectedMode() {
        var selView = $('.peopleView .viewMode').find('.ui-selected');
        if (selView.hasClass('listView')) {
            return 1;
        }
        else if (selView.hasClass('iconView')) {
            return 0;
        }
        else if (selView.hasClass('detailView')) {
            return 2;
        }

        return -1;
    }

    function savePersonInfo() {
        var data = { pId: contextInfo.SelectedPersonId };

        var set = $('#tabs-general');
        var name = set.attr('data-fieldGroup');
        var template = configHelper.getPeopleCategoryFieldSet(personInfoViewModel.CatName, name);
        var fsetData = uiFieldFactory.getFieldSetData(set, template);

        data.fsetId = fsetData.Id;
        data.fdata = JSON.stringify({ fsetType: fsetData.fsetType, fdata: fsetData.fdata });

        doAjax('/Meres/People/AddOrUpdatePersonFieldSet', function (evt) {
            $(set).attr('data-fsetId', evt);
            setStatus({ type: 'info', msg: 'Saved' });
        }, data, 'POST');
    }

    function installCombobox() {

        if ($('#cmbCategories').length == 0)
            return;
        dhtmlXComboFromSelect('cmbCategories');
    }

    $('.actionBar .deletePerson').click(function () {
        var url = '/Meres/People/GetPerson';
        var pId = $('.personInfoView').attr('data-personId');
        doAjax(url, showForm, "personId=" + pId);

        function showForm(evt) {
            $("#dialog-form").html("Are you sure you want to delete this person:" + evt.Name);

            $("#dialog-form").dialog({
                autoOpen: false,
                height: 200,
                width: 400,
                modal: true,
                buttons: {
                    OK: executeDelete,
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            });

            $("#dialog-form").dialog("open");
        }

        function executeDelete() {
            doAjax("/Meres/People/RemovePerson", function () {
                $('#dialog-form').dialog("close");
                Messenger.broadcast(this, Messenger.PERSON_DELETED, pId);

            }, "personId=" + pId)
        }
    });

    function installPersonInfo() {
        $('.personInfoView .personInfoTabs').tabs();
        innerLayout = $('#mainArea').layout({
            onresize: function () {
                infofuncLayout.resizeAll();
                $.layout.callbacks.resizePaneAccordions();
            }
        });

        innerLayout.sizePane("south", $('#mainArea').height() / 2);

        infofuncLayout = $('#infofunc').layout({ east__onresize: $.layout.callbacks.resizePaneAccordions });
        $("#peopleFunctionAccordion").accordion({ fillSpace: true });
        infofuncLayout.sizePane("east", "180");

        $('#canLogin').click(function () {
            if ($(this).is(':checked'))
                $('#canLoginProperties').css('visibility', 'visible');
            else
                $('#canLoginProperties').css('visibility', 'collapse');
        });

        var data = undefined;

        var set = personInfoViewModel.fieldSets.singleOrDefault(function (item) {
            return item.fsetData.fsetType == 'fsetType1';
        });
        if (set != undefined) {
            data = {
                Id: set.fsetId,
                fdata: set.fsetData.fdata
            };
        }
        $('.personInfoView').find('[data-fieldGroup]').each(function () {
            var name = $(this).attr('data-fieldGroup');
            var template = configHelper.getPeopleCategoryFieldSet(personInfoViewModel.CatName, name);
            uiFieldFactory.renderFieldSet(this, template, data);
        });

        $('.personInfoView .selectableItems').selectable();
    }

    var selPersonId = undefined;
    function setSelPersonId(pId) {
        var old = selPersonId;
        selPersonId = pId;
        if (old == selPersonId)
            return;

        preventSelPerson = true;
        var selView = $('.peopleView .viewMode').find('.ui-selected');

        $("#peopleView .personSelector").personSelector('option', 'setSelPerson', selPersonId);

        if (selView.hasClass('detailPersonView')) {
            if (!preventOpenDetail)
                openPersonDetail(selPersonId);
        }
        else if (selView.hasClass('listView')) {
            $("#peopleList").jqGrid('setSelection', selPersonId, false);
        }
        else if (selView.hasClass('iconView')) {
            var sel = $(".peopleView .cardView").find('[data-personId=' + selPersonId + ']');
            JsUtil.selectSelectableElements($(".peopleView .cardView"), sel);
        }

        preventSelPerson = false;
    }

    function getSelPersonId() {
        return selPersonId;
    }

    var contextInfo = {};

    var personInfoViewModel = undefined;

    function openPersonDetail(personId) {
        contextInfo = { Module: 'PersonDetail', SelectedPersonId: personId };
        personId = personId == undefined ? 0 : personId;
        var url = '/Meres/People/PersonInfo?personId=' + personId;
        doAjax(url,
        function (evt) {
            $('#peopleView .functionContent').html(evt.Html);
            personInfoViewModel = evt.ViewModel;

            for (var i = 0; i < evt.ViewModel.fieldSets.length; i++) {
                var raw = evt.ViewModel.fieldSets[i].fsetData;
                evt.ViewModel.fieldSets[i].fsetData = JSON.parse(raw);
            }

            installPersonInfo();
        });
    }

    var preventOpenDetail = false;

    function openPeopleList(opts) {
        $('#peopleView .functionContent').html('<table id="peopleList"></table><div id="peopleListPager" />');
        var $content = $('#peopleView .functionContent');
        var catId = opts != undefined && opts.catIds != undefined && opts.catIds.length != 0 ? opts.catIds[0] : -1;

        $("#peopleList").jqGrid({
            url: '/Meres/People/PeoplejqGridQuery',
            postData: { catId: catId },
            datatype: "json",
            mtype: "POST",
            colNames: ["Id", "Name", "Category", "Birthday", "CreatedDate"],
            colModel: [
                            { name: "Id", index: "Id", width: 30, align: "center", vertical: "middle" },
                            { name: "Name", index: "Name", width: 100, align: "left", editable: true, classes: 'jqGridSelCol' },
                            { name: "Category", index: "Category", width: 100, align: "Left" },
                            { name: "Birthday", index: "Birthday", width: 100, align: "center", editable: true, sorttype: "date", formatoptions: { newformat: 'd.m.Y' }, formatter: 'date' },
                            { name: "CreatedDate", index: "CreatedDate", width: 100, align: "center", editable: true, sorttype: "date", formatoptions: { newformat: 'd.m.Y' }, formatter: 'date' }
            ],
            // Grid total width and height
            width: $content.width() - 2,
            height: $content.height() - 70 - 2,

            // Paging                    
            pager: $("#peopleListPager"),
            rowNum: 20,
            rowList: [5, 10, 20, 50, 100],
            viewrecords: true,
            // Default sorting
            sortname: "Id",
            sortorder: "asc",

            // Grid caption
            caption: "PEOPLE LIST",

            serializeRowData: function (postData) {
                var d = postData.ModifiedDate;
                postData.ModifiedDate = '11/28/1984';
                return postData;
            },

            editurl: '/Meres/People/EditPersonjqGrid',
            onSelectRow: function (rowid, status) {
                //preventOpenDetail = true;
                //setSelPersonId(rowid);
                //preventOpenDetail = false;
            },
            onCellSelect: function (rowId, iCol, cellcontent, e) {
                preventOpenDetail = true;
                setSelPersonId(rowId);
                preventOpenDetail = false;

                if (iCol != 1)
                    return;

                JsUtil.selectSelectableElements($(".peopleView .viewMode"), $(".peopleView .viewMode").children()[2]);
                openPersonDetail(rowId);
            }

        }).navGrid("#peopleListPager",
                    {
                        refresh: true, add: true, edit: true, del: true
                    },
                    {}, // settings for edit
                    {}, // settings for add
                    {}, // settings for delete
                    { sopt: ["cn"] } // Search options. Some options can be set on column level
                 );

        $("#peopleList").jqGrid('navGrid', "#peopleList", { edit: false, add: false, del: false });
        $("#peopleList").jqGrid('inlineNav', "#peopleList");

    }

    function openCardView(opts) {
        var catId = opts != undefined && opts.catIds != undefined && opts.catIds.length != 0 ? opts.catIds[0] : -1;
        var url = '/Meres/People/PeopleCardView?catId=' + catId;
        doAjax(url,
        function (evt) {
            $('#peopleView .functionContent').html(evt.Html);
            $('#peopleView .cardView').selectable({
                selected: function (evt1, ui) {
                    var id = $(ui.selected).attr('data-personId');
                    preventOpenDetail = true;
                    setSelPersonId(id);
                    preventOpenDetail = false;
                }
            });
            $('#peopleView .cardView .jqGridSelCol').click(function (evt1) {
                alert(evt1);
            });
        });
    }

    Messenger.register(Messenger.PERSON_ADDED, function (sender, input) {
        openPersonDetail(input);
    });

    Messenger.register(Messenger.PERSON_DELETED, function (sender, input) {
        $('#peopleView .functionContent').html('FUNCTION');
    });

    JsUtil.selectSelectableElements($(".peopleView .viewMode"), $(".peopleView .viewMode").children()[0]);
}
